package shuogg.xstream.demo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;

import com.thoughtworks.xstream.XStream;

/**
 * @description 将javabean转为xml的工具类
 *
 * @author linshuo
 *
 */
public class XStreamUtils {

    /**
     * @description 最基本的一个Bean转xml, 直接把一个bean实例丢进来就能生成xml的string
     * @param bean
     * @return
     */
    public static String getXmlStrByBean(Object bean) {
        XStream xstream = new XStream();
        String xmlStr = xstream.toXML(bean);
        return xmlStr;
    }

    /**
     * @description 跟getXmlStrByBean效果基本一样, 用list是方便用户理解
     * @param beanList
     * @return
     */
    @SuppressWarnings(value = { "rawtypes" })
    public static String getXmlStrByBeanlist(List beanList) {
        XStream xstream = new XStream();
        String xmlStr = xstream.toXML(beanList);
        return xmlStr;
    }

    /**
     * @description 由于bean的类名又臭又长, 所以需要两个list来简化
     * @param bean
     * @param classList
     *            被简化的class
     * @param newNameList
     *            新名字
     * @return
     * @throws Exception 
     */
    @SuppressWarnings(value = { "rawtypes" })
    public static String getXmlStrByBeanAlterClassname(Object bean, Class[] classList, String[] newNameList) throws Exception {
        if (classList.length != newNameList.length) {
            throw new lengthMatchErrorException("两个list的长度必须相同");
        }
        XStream xstream = new XStream();
        for (int i = 0; i < classList.length; i++) {
            xstream.alias(newNameList[i], classList[i]);
        }
        String xmlStr = xstream.toXML(bean);
        return xmlStr;
    }
    
    /**
     * @description 将string保存到磁盘指定位置
     * @param xmlStr
     * @param saveUrl
     */
    public static void saveAsXmlfile(String xmlStr, String saveUrl) {
        PrintWriter pw;
        try {
            pw = new PrintWriter(new File(saveUrl));
            pw.print(xmlStr);
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
}

class lengthMatchErrorException extends RuntimeException{
    public lengthMatchErrorException(String errorMsg) {
        super(errorMsg);
    }
}
